"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

import os
import signal
import platform
import traceback
from msnp.logger import Logger

OS_WINDOWS = "Windows"

def __getLinuxPIDForProcessName(processName):
    """Retrieves the PID of the current application if its a Linux workstation.
    
    Makes a system call to get a list of running applications.
    Retrieves the PID out of this information.
    
    Returns:
        The retrieved PID is returned or None if an error occurred.
    """
    try:
        for line in os.popen("ps -A | grep " + processName):
            fields = line.split()
            if len(fields) == 4:
                pid = fields[0]
                process = fields[3]
                if process == processName:
                    return pid
    except:
        Logger.info("Exception while searching Linux process id for name '" + processName + "'")
        Logger.info(traceback.format_exc())
    #process not running
    return None

#TODO not tested
def __getWindowsPIDForProcessName(processName):
    """Retrieves the PID of the current application if its a Windows workstation.
    
    Retrieves a list of running processes.
    Retrieves the PID of this application out of this information.
    
    Returns:
        The retrieved PID is returned or None if an error occurred.
    """
    try:
        #TODO einkommentieren!!
        Logger.info("__getWindowsPIDForProcessName - implementation is out-commented")
#        import wmi
#        c = wmi.WMI ()
#        for process in c.Win32_Process ():
#            pName = process.Name
#            if pName.find(processName) > 0:
#                return process.ProcessId
    except:
        Logger.info("Exception while searching Windows process id for name '" + processName + "'")
        Logger.info(traceback.format_exc())
    return None

#TODO
def __startPlayerProcessWindows(processName):
    """Starts the given media player if this is a Windows workstation.
    
    Args:
        processName: The name of the player, that has to be started.
    """
    pass

def __startPlayerProcessLinux(processName):
    """Starts the given media player if this is a Linux workstation.
    
    Makes a system call to start the player.
    
    Args:
        processName: The name of the player, that has to be started.
    """
    Logger.info("Starting player with linux command: '" + processName + "'")
    os.system(processName)
              
def getPIDForPlayer(playerInstance):
    """Retrieves the PID of the given running player.
    
    Args:
        playerInstance: The name of the player.
        
    Returns:
        It returns the correct PID of the running media player.
    """
    oSystem = platform.system()
    Logger.info("Your running system is: '" + oSystem + "'")
    if oSystem == OS_WINDOWS:
        return __getWindowsPIDForProcessName(playerInstance.getPNameWindows())
    return __getLinuxPIDForProcessName(playerInstance.getPNameLinux())

def startPlayerProcess(playerInstance):
    """Starts the given player.
    
    Args:
        playerInstance: The name of the player.
    """
    oSystem = platform.system()
    Logger.info("Your running system is: '" + oSystem + "'")
    if oSystem == OS_WINDOWS:
        __startPlayerProcessWindows(playerInstance.getPNameWindows())
    else:
        __startPlayerProcessLinux(playerInstance.getPNameLinux())

#TODO should be platform independend - test it
def killProcessById(pid):
    """Kills a certain process by its PID.
    
    Sends a SIGHUP signal to the process.
    
    Args:
        pid: The pid of the process to be killed as String.
    """
    try:
        if pid != None:
            Logger.info("Trying to kill process with pid '" + str(pid) + "'")
            # Kill the Process. Change signal.SIGHUP to signal.SIGKILL if you like
            os.kill(int(pid), signal.SIGHUP)
        else:
            Logger.info("pid is None -> no instance running")
    except:
        Logger.info("Exception while killing pid '" + str(pid) + "'")
        Logger.info(traceback.format_exc())
